package kr.hkit.powerjava.chapter23;

public class ThreadControl {
	static void print(String msg){
		String threadname = Thread.currentThread().getName();
		System.out.format("%s: %s\n", threadname, msg);
	}
	
	private static class MessageLoop implements Runnable{
		@Override
		public void run() {
			String[] message = { "Pride will have a fall",
					"Power is dangerous unless you have humility.",
					"Office changes manners.",
					"Empty vessels make the most sound."
			};
			for (int i = 0; i < message.length; i++) {
				print(message[i]);
				try {
					Thread.sleep(2000);	
				} catch (InterruptedException e) {
					print("아직 끝나지 않았어요!");
				}
			}
		}	//end of method run()
	}//end of class MessageLoop();
	
	public static void main(String[] args) throws InterruptedException {	//예외 처리 전가
		int tries = 0;	//시도횟수
		
		ThreadControl.print("추가적인 쓰레드를 시작을 합니다.");
		Thread t = new Thread(new MessageLoop());
		t.start();
		
		ThreadControl.print("추가적인 쓰레드를 끝나기를 기다립니다.");
		
		while(t.isAlive()) {
//			System.out.println("is Alive Call");
			ThreadControl.print("아직 기다립니다.");
			t.join(1000);	
			tries++;	//1씩 증가하였음
//			System.out.println(tries);
			if(tries > 2) {	//2초동안 기다리다
				ThreadControl.print("참을 수 없네요!! 맙소사!");
				t.interrupt();
				t.join();
			}
			
		}
		ThreadControl.print("메인 스레드 종료");
		
	}
}